package it.xiuxian.lib.utils;

import android.annotation.SuppressLint;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.content.res.AppCompatResources;

import java.lang.reflect.Field;
import java.util.Objects;

/*
 *@Description: 编辑框工具类
 *@Author: hl
 *@Time: 2019/2/20 9:29
 */
public class EditTextUtil {
    /**
     * 代码设置光标颜色
     *
     * @param editText 你使用的EditText
     * @param color    光标颜色
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void setCursorDrawableColor(EditText editText, int color) {
        try {
           @SuppressLint("SoonBlockedPrivateApi") Field fCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");//获取这个字段
            fCursorDrawableRes.setAccessible(true);//代表这个字段、方法等等可以被访问
            int mCursorDrawableRes = fCursorDrawableRes.getInt(editText);
            @SuppressLint("DiscouragedPrivateApi") Field fEditor = TextView.class.getDeclaredField("mEditor");
            fEditor.setAccessible(true);
            Object editor = fEditor.get(editText);

            Class<?> clazz = null;
            if (editor != null) {
                clazz = editor.getClass();
            }
            Field fCursorDrawable = null;
            if (clazz != null) {
                fCursorDrawable = clazz.getDeclaredField("mCursorDrawable");
            }
            if (fCursorDrawable != null) {
                fCursorDrawable.setAccessible(true);
            }

            Drawable[] drawables = new Drawable[2];
            drawables[0] = AppCompatResources.getDrawable(editText.getContext(),mCursorDrawableRes);
            drawables[1] = AppCompatResources.getDrawable(editText.getContext(),mCursorDrawableRes);
            Objects.requireNonNull(drawables[0]).setColorFilter(color, PorterDuff.Mode.SRC_IN);//SRC_IN 上下层都显示。下层居上显示。
            Objects.requireNonNull(drawables[1]).setColorFilter(color, PorterDuff.Mode.SRC_IN);
            if (fCursorDrawable != null) {
                fCursorDrawable.set(editor, drawables);
            }
        } catch (Throwable ignored) {
        }
    }
}
